package com.woniu.controller;

import com.github.pagehelper.PageInfo;
import com.woniu.common.JsonResult;
import com.woniu.constant.SystemConstant;
import com.woniu.pojo.User;
import com.woniu.service.UserService;
import com.woniu.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;


    @RequestMapping("/findUser")
    public Map findUser(@RequestParam(value="page",defaultValue = "1",required = false)Integer
                                currentPage , @RequestParam(value="rows",defaultValue = "5",required = false)
                                Integer pageSize, UserVO userVO){
        List<User> userList = userService.findUserList(currentPage,pageSize,userVO);
        PageInfo<User> pageInfo = new PageInfo<>(userList);
        Map result = new HashMap();
        result.put("rows",pageInfo.getList());
        result.put("total",pageInfo.getTotal());
        return result;
    }

    @RequestMapping("/save")
    public String save(User user){
        try {
            userService.saveUser(user);
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
    }


    @RequestMapping("/delete")
    public String delete(String keys){
        System.out.println(keys);
        String arr[]=keys.split(",");
        System.out.println(arr.toString());
        Integer[] primarykeys=new Integer[arr.length];
        for (int i=0;i<arr.length;i++){
            //System.out.println(arr[i]);
           // System.out.println(Integer.parseInt(arr[i]));
            primarykeys[i]=Integer.parseInt(arr[i]);
           // System.out.println(primarykeys[i]);
        }

        userService.deleteUser(primarykeys);
        return "删除成功";
    }

    @RequestMapping("/doLogin")
    public JsonResult doLogin(User user, HttpSession session){
        User _user = userService.findUser(user);
        if(_user != null){
            session.setAttribute(SystemConstant.CURRENT_USER,_user);
            return JsonResult.ok("success");
        }else{
            return JsonResult.erro("用户名或密码错误");
        }
    }
}
